﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GS.Cricket.Service.Impl.NHibernate;
using NHibernate;
using NHibernate.Criterion;

namespace GS.Cricket.Service.Impl
{
    public class TeamService : ITeamService
    {
        #region ITeamService Members

        public int Add(Entities.Team team)
        {
            var existing = (Entities.Team)team.Name.GetByName<Entities.Team>();
            if (existing == null)
            {
                return (int)team.Add<Entities.Team>();
            }
            else
            {
                throw new NonUniqueObjectException("Team already exist", team, team.Name);
            }
        }

        public void Update(Entities.Team team)
        {
            team.Update<Entities.Team>();
        }

        public void Delete(int teamId)
        {
            var existing = (Entities.Team)teamId.GetById<Entities.Team>();
            if (existing != null)
            {
                existing.Delete<Entities.Team>();
            }
        }

        public Entities.Team GetById(int teamId)
        {
            return (Entities.Team) teamId.GetById<Entities.Team>();
        }

        public IEnumerable<Entities.Team> GetByGroup(int groupId)
        {
            using (ISession session = NHibernateHelper<Entities.Team>.OpenSession())
            {
                var result = session
                    .CreateCriteria(typeof(Entities.Team))
                    .Add(Restrictions.Eq("Group", groupId))
                    .List<Entities.Team>();
                return result;
            }
        }

        public IEnumerable<Entities.Team> GetAll()
        {
            return this.GetAll<Entities.Team>();
        }

        #endregion
    }
}
